//
//  YSPComposeController.swift
//  Weibo Demo
//
//  Created by 朴裕识 on 15/12/28.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class YSPComposeController: UIViewController {
    
    private var toolBarConstraint: NSLayoutConstraint?

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupNavBar()
        setupNavTitle()
        setupTextView()
        setupToolBar()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    private func setupTextView() {
        view.addSubview(textView)
        textView.ff_Fill(view, insets: UIEdgeInsets.init(top: 0, left: 0, bottom: 49, right: 0))
        textView.placeholderText = "为了部落..."
        textView.delegate = self
    }
    
    private func setupToolBar() {
        view.addSubview(toolBar)
        
        let constraint = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 49))
        toolBarConstraint = toolBar.ff_Constraint(constraint, attribute: NSLayoutAttribute.Bottom)
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        
        var itemArray = [UIBarButtonItem]()
        
        for dict in itemSettings {
            //给按钮添加图片
            let imageName = dict["imageName"]!
            let item = UIBarButtonItem(imageName: imageName)
            itemArray.append(item)
            
            let bounce = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            itemArray.append(bounce)
            
            //给按钮添加点击事件
            let action = dict["action"]!
//            let button = item.customView as! UIButton
            
            (item.customView as! UIButton).addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
        }
        
        itemArray.removeLast()
        
        toolBar.items = itemArray
    }
    
    private func setupNavTitle() {
        let prefix = "发微博"
        if let name = YSPUserAccount.loadUserAccount()?.screen_name {
            let text = prefix + "\n" + name
            
            let label = UILabel()
            label.numberOfLines = 0
            label.textColor = UIColor.blackColor()
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(14)
            
            let attributeText = NSMutableAttributedString(string: text)
            //获取用户名称在文本里的范围
            let nameRange = (text as NSString).rangeOfString(name)
            attributeText.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            attributeText.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(11), range: nameRange)
            label.attributedText = attributeText
            label.sizeToFit()
            navigationItem.titleView = label
        } else {
            //没有获取到用户名
            navigationItem.title = "发微博"
        }
    }

    private func setupNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    /*
    notification: NSConcreteNotification 0x7f8e61cfa470 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
    UIKeyboardAnimationCurveUserInfoKey = 7;
    UIKeyboardAnimationDurationUserInfoKey = "0.25";    // 动画时间
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";   // 键盘最终的位置
    UIKeyboardIsLocalUserInfoKey = 1;
    }}
    */
    //MARK: - 各种事件的触发
    @objc private func keyboardWillChangeFrame(notification: NSNotification) {
//        print("\(notification)")
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        toolBarConstraint?.constant = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
//        print("\(toolBarConstraint?.constant)")
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    @objc private func close() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendStatus() {
        print("发送微博")
    }
    
    //MARK: - toolBar点击事件
    // MARK: - toolBar点击事件
    func picture() {
        print("图片")
    }
    
    func trend() {
        print("#")
    }
    
    func mention() {
        print("@")
    }
    
    /// 切换表情键盘
    func emoticon() {
        //下面这样代码并不能让我们点击表情按钮时弹出表情键盘，原因是
        //系统在弹出键盘之前 弹出键盘之前 弹出键盘之前
        //如果inputView == nil 则弹出系统键盘
        //如果inputView != nil 则弹出我们的键盘
        //因为我们是点了这个方法之后，inputView才不等于nil,所以会造成一开始显示系统的，拉一下textView之后，键盘缩了回去，这时候系统发现inputView != nil，就弹出我们的键盘
//        textView.inputView = emoticonVC.view
        
        //改进之后
        //点击表情按钮的时候先缩回键盘
        textView.resignFirstResponder()

       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
        
        //如果目前是系统键盘，就赋值我们的键盘；如果是我们的键盘，就赋值系统的键盘
        self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
        self.textView.becomeFirstResponder()
        }
    }
    
    func add() {
        print("加号")
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    
    //MARK: - 懒加载
    private lazy var toolBar: UIToolbar = {
        let toolBar = UIToolbar()
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        return toolBar
    }()
    
    private lazy var textView: YSPPlaceholderView = {
        let textView = YSPPlaceholderView()
        textView.font = UIFont.systemFontOfSize(18)
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.alwaysBounceVertical = true
        return textView
    }()
    
    private lazy var emoticonVC: YSPTextViewController = YSPTextViewController(textView: self.textView)

}

extension YSPComposeController:UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
